package middleware

import (
	"api/appconfig"
	"api/internal/types"
	"api/pkg"
	"context"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
)

type AuthTokenMiddleware struct {
}

func NewAuthTokenMiddleware() *AuthTokenMiddleware {
	return &AuthTokenMiddleware{}
}

func (m *AuthTokenMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		token := r.Header.Get("token")
		if token == "" {
			httpx.OkJsonCtx(r.Context(), w, &types.Response{
				Code:    -1,
				Message: "未检测到 token",
				Data:    nil,
			})
			return
		}
		//解析token
		payload, err := pkg.ParseJwtToken(appconfig.AppConf.AccessSecret, token)
		if err != nil {
			httpx.OkJsonCtx(r.Context(), w, &types.Response{
				Code:    -2,
				Message: "token 解析失效",
				Data:    nil,
			})
			return
		}
		value := context.WithValue(r.Context(), "userId", payload)
		next(w, r.WithContext(value))
	}
}
